package com.ziyueyuwen.xiniao.controller.product.order;

import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.HttpResUtil;
import com.suyeer.basic.util.LogUtil;
import com.suyeer.fastwechat.util.FwUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.product.ZyCouponDO;
import com.ziyueyuwen.xiniao.enums.HttpStatusEnum;
import com.ziyueyuwen.xiniao.service.CouponService;
import com.ziyueyuwen.xiniao.service.OrderService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.List;

import static com.ziyueyuwen.xiniao.base.BaseUtil.*;
import static com.ziyueyuwen.xiniao.enums.ParamTypeEnum.INTEGER_GT_0;
import static com.ziyueyuwen.xiniao.util.ConstUtil.*;

/**
 * @author jun 2019/2/25
 */
@Validated
@Controller
@RequestMapping("/product/order")
public class ProductOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CouponService couponService;

    @RequestMapping(value = "/list_coupon.do", method = RequestMethod.POST)
    public void listCoupon(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<ZyCouponDO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取优惠券列表");
        try {
            List<ZyCouponDO> list = couponService.listByUser(hrc.getUserInfo().getUserAccount());
            saveSuccessMsgAndData(hrc, list);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/enable_use_coupon.do", method = RequestMethod.POST)
    public void enableUse(@RequestParam(PARAM_OUT_TRADE_NO) String outTradeNo,
                          HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("优惠券恢复可用");
        try {
            // check
            checkParam(PARAM_OUT_TRADE_NO, outTradeNo);
            // do.
            if (!hrc.isWxLogin()) {
                throw new Exception("账号未登陆!");
            }
            orderService.enableUse(outTradeNo, hrc.getWxUserInfo().getUnionid());
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_prepay_info.do", method = RequestMethod.POST)
    public void getPrepayInfo(@RequestParam(PARAM_PRODUCT_ID) Integer productId,
                              @RequestParam(PARAM_ADDRESS_ID) Integer addressId,
                              @RequestParam(value = PARAM_COUPON_ID, required = false) Integer couponId,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("微信支付");
        try {
            // check.
            checkParam(INTEGER_GT_0, PARAM_PRODUCT_ID, productId);
            checkParam(INTEGER_GT_0, PARAM_ADDRESS_ID, addressId);
            // do.
            if (couponId != null && couponId.equals(0)) {
                couponId = null;
            }
            if (!hrc.isLogin() || !hrc.isWxLogin()) {
                throw new Exception("用户未登陆!");
            }
            JSONObject retObj = orderService.getPrepayInfo(hrc, productId, addressId, couponId);
            saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    /**
     * 微信公众号支付回调
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/notify.do", method = RequestMethod.POST)
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<String> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("公众号支付结果通知");
        try {
            // 读取通知内容
            String notifyContent = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
            LogUtil.info("微信支付回调: {}", notifyContent);
            orderService.payBack(notifyContent);
            saveSuccessMsgAndData(hrc, FwUtil.getPaySuccessNoticeReturnXmlContent());
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, HttpStatusEnum.SERVER_ERROR.getCode(), FwUtil.getPayFailNoticeReturnXmlContent(), e);
        } finally {
            HttpResUtil.writeOnlyResult(hrc);
        }
    }

}
